//axios二次封装
import axios from 'axios'
//导入 router 
import $router from '../router/index'
import { Button,Toast,Loading } from 'vant';

//设置请求拦截器
axios.interceptors.request.use((config)=>{
    //显示loading
     Toast({message:'加载中...',type:'loading',duration:0})
    //给config设置请求头
    //每次发请求, 都会自动执行这个代码, 添加请求头
    config.headers['Authorization'] = "Bearer "+localStorage.getItem("token");
    //添加其他请求头
    config.headers['xxxx'] = "";

    return config;
},(error)=>{
    return Promise.reject(error);
})

//设置响应拦截器
axios.interceptors.response.use((response)=>{
    // if( response.data.token && response.data.code == 200 ){
    //     localStorage.setItem('token', res.data.token );
    // }
    Toast.clear()
    return response;
},(error)=>{
    Toast.clear()
    if(error.response.status == 404){

        alert("请求路径有误!");
    }
    else if( error.response.status == 401 ){
        alert("身份认证失败,登录过期!");
        //删除本地token
        localStorage.removeItem('token');
        //重定向到登录页
        $router.push('/login');
        
    }
    else if( error.response.status == 500 ){
        alert("服务器内部错误!");
    }
    return Promise.reject(error);
})

export default axios;